package com.zmc.admin.infrastructure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zmc.admin.infrastructure.constant.UserConstants;
import com.zmc.admin.infrastructure.entity.SysRoleEntity;
import com.zmc.admin.infrastructure.bean.query.SysDeptQuery;
import com.zmc.admin.infrastructure.service.SysRoleService;
import com.zmc.admin.infrastructure.bean.vo.menu.TreeSelect;
import com.zmc.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zmc.admin.infrastructure.dao.SysDeptDao;
import com.zmc.admin.infrastructure.entity.SysDeptEntity;
import com.zmc.admin.infrastructure.service.SysDeptService;


@Service("sysDeptService")
public class SysDeptServiceImpl extends ServiceImpl<SysDeptDao, SysDeptEntity> implements SysDeptService {

    @Autowired
    private SysRoleService roleService;


    @Override
    public List<SysDeptEntity> selectDeptList(SysDeptQuery dept) {
        LambdaQueryWrapper<SysDeptEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(dept.getDeptName()), SysDeptEntity::getDeptName, dept.getDeptName())
                .eq(StringUtils.isNotEmpty(dept.getStatus()), SysDeptEntity::getStatus, dept.getStatus())
                .eq(SysDeptEntity::getDelFlag, "0");
        return list(wrapper);
    }

    @Override
    public boolean checkDeptNameUnique(SysDeptEntity dept) {
        long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        QueryWrapper<SysDeptEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("dept_name", dept.getDeptName())
                .eq("parent_id", dept.getParentId())
                .eq("del_flag", "0");

        SysDeptEntity info = getOne(wrapper);
        if (StringUtils.isNotNull(info) && info.getDeptId() != deptId) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        return baseMapper.selectNormalChildrenDeptById(deptId);
    }

    @Override
    public boolean hasChildByDeptId(Long deptId) {
        int result = baseMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    @Override
    public boolean checkDeptExistUser(Long deptId) {
        int result = baseMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    @Override
    public List<Long> selectDeptListByRoleId(Long roleId) {
        SysRoleEntity role = roleService.getById(roleId);
        return baseMapper.selectDeptListByRoleId(roleId, role.getDeptCheckStrictly() == 1);
    }

    @Override
    public List<TreeSelect> selectDeptTreeList() {
        List<SysDeptEntity> deptList = list();
        return buildDeptTreeSelect(deptList);
    }

    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDeptEntity> depts)
    {
        List<SysDeptEntity> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDeptEntity> buildDeptTree(List<SysDeptEntity> depts)
    {
        List<SysDeptEntity> returnList = new ArrayList<SysDeptEntity>();
        List<Long> tempList = depts.stream().map(SysDeptEntity::getDeptId).collect(Collectors.toList());
        for (SysDeptEntity dept : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDeptEntity> list, SysDeptEntity t)
    {
        // 得到子节点列表
        List<SysDeptEntity> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDeptEntity tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDeptEntity> getChildList(List<SysDeptEntity> list, SysDeptEntity t)
    {
        List<SysDeptEntity> tlist = new ArrayList<SysDeptEntity>();
        Iterator<SysDeptEntity> it = list.iterator();
        while (it.hasNext())
        {
            SysDeptEntity n =  it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDeptEntity> list, SysDeptEntity t)
    {
        return getChildList(list, t).size() > 0;
    }

    public List<SysDeptEntity> selectDeptList(SysDeptEntity dept){
        return baseMapper.selectDeptList(dept);
    }

}